package com.tanhua.manage.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.tanhua.manage.mapper.LoginUserMapper;
import com.tanhua.manage.pojo.Admin;
import com.tanhua.manage.service.LoginService;
import com.tanhua.manage.vo.LoginUserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("system/users")
@Slf4j
public class LoginController {

    @Autowired
    private LoginUserMapper loginUserMapper;

    @Autowired
    private LoginService loginService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 用户登录
     * @param param
     * @return
     */
    @PostMapping("login")
    public ResponseEntity<Map<String,String>> userLogin(@RequestBody Map<String,String> param,HttpServletRequest request,HttpServletResponse response) throws JsonProcessingException {

        String username = param.get("username");
        String password = param.get("password");
        String verificationCode = param.get("verificationCode");
        HttpSession session = request.getSession();
        String uuid = (String) session.getAttribute("uuid");

        String redisKey = "CHECK_" + uuid;

        String code = redisTemplate.opsForValue().get(redisKey);

        //验证码错误
        if (!StrUtil.equals(verificationCode,code)){
            log.error("登录失败");
            return null;
    }

        String token = loginService.checkUser(username,password);

        if (token == null){
            log.error("token不合法");
            return null;
        }

        session.removeAttribute("uuid");
        redisTemplate.delete(redisKey);
        Map<String,String> map = new HashMap<>();
        map.put("token",token);


        return ResponseEntity.ok(map);
    }


    @PostMapping("profile")
    public LoginUserVo getProfile(@RequestHeader("Authorization") String token, HttpServletRequest request){
        
        String[] split = token.split(" ");
        token = split[1];

        try {
            Admin admin = loginService.queryUserByToken(token);
             LoginUserVo loginUserVo = loginService.getLoginUser(admin.getId());

            return loginUserVo;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 用户登出
     * @param token
     */
    @PostMapping("logout")
    public ResponseEntity<String> LogOut(@RequestHeader("Authorization") String token, HttpServletRequest request) {

        String[] split = token.split(" ");
        String token2 = split[1];

        try {
            return ResponseEntity.ok(null);
        } catch (Exception e) {
            log.error("退出失败",e);
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }


    @GetMapping("verification")
    public void getCode(@RequestParam String uuid, HttpServletRequest request,HttpServletResponse response) throws IOException {

        String code1 = "1234";
        HttpSession session = request.getSession();
        session.setAttribute("uuid",uuid);

        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(160, 66);
        try {
            lineCaptcha.write(response.getOutputStream());
            String code = lineCaptcha.getCode();
            lineCaptcha.write(response.getOutputStream());

            String redisKey = "CHECK_" + uuid;


            redisTemplate.opsForValue().set(redisKey,code1,60*3,TimeUnit.SECONDS);

        } catch (IOException e) {
            log.error("获取图形验证码失败",e);
        }finally {
            response.getOutputStream().close();
        }
    }

}